#include "../main.h"
#include <bits/types/struct_timeval.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define PATH_FIFO "/home/yujiu/fifo"
void if_error(int,char*,int);
int main()
{
    int res=0;
    res=access(PATH_FIFO,F_OK);
    if_error(res,"access",-1);
    int fd=open(PATH_FIFO,O_WRONLY);
    if_error(fd,"read",fd);
    char buf[128]={0};
    ssize_t byte=0;

    fd_set readfd,readfd_bak,writefd,writdfd_bak;
    struct timeval timeout,timeout_bak;
    timeout.tv_sec=0;
    timeout.tv_usec=0;

    FD_ZERO(&readfd);
    FD_SET(0,&readfd);
    FD_ZERO(&writefd);
    FD_SET(fd,&writefd);
    while(1){
        timeout_bak=timeout;
        readfd_bak=readfd;
        writdfd_bak=writefd;

        res=select(3,&readfd_bak,&writdfd_bak,NULL,&timeout_bak);
        if(res==-1){
            perror("select:");
            exit(1);
        }else if(res==0){
            continue;
        }else{
            if(FD_ISSET(0,&readfd_bak)){
                memset(buf,0,sizeof(buf));
                fgets(buf,sizeof(buf),stdin);
                buf[strlen(buf)-1]='\0';
                if(FD_ISSET(fd,&writdfd_bak)==0){
                    byte=write(fd,buf,strlen(buf));
                    if_error(byte,"write",fd);
                    if(strcmp(buf,"exit")==0){
                        break;
                    }
                }else{
                    printf("管道无法写数据：\n");
                }
            }
        }
    }
    close(fd);
    return 0;
}
void if_error(int res,char* str,int fd){
    if(res==-1){
        perror(str);
        if(fd!=-1){
            close(fd);
        }
        exit(1);
    }
}
